package com.CommunityHub.kiana.dao;


import com.CommunityHub.kiana.po.MemberDetail;
import com.CommunityHub.kiana.utils.DBUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class MemberDetailDAO {

    /**
     * 根据会员ID查找会员详情
     *
     * @param memberId 会员ID
     * @return MemberDetail 对象，如果没有找到返回 null
     * @throws SQLException SQL异常
     */
    public MemberDetail findById(int memberId) throws SQLException {
        String sql = "SELECT * FROM member_detail WHERE member_id = ?";
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;

        try {
            conn = DBUtil.getConnection();
            ps = conn.prepareStatement(sql);
            ps.setInt(1, memberId);
            rs = ps.executeQuery();

            if (rs.next()) {
                MemberDetail member = new MemberDetail();
                member.setMemberId(rs.getInt("member_id"));
                member.setRealName(rs.getString("real_name"));
                member.setGender(rs.getString("gender"));
                member.setBirthDate(rs.getDate("birth_date"));
                member.setPhone(rs.getString("phone"));
                member.setIdCard(rs.getString("id_card"));
                member.setContactName(rs.getString("contact_name"));
                member.setContactPhone(rs.getString("contact_phone"));
                member.setMemberType(rs.getString("member_type"));
                member.setRemark(rs.getString("remark"));
                return member;
            }
            return null;
        } finally {
            DBUtil.close(conn, ps, rs);
        }
    }

    /**
     * 更新会员信息
     *
     * @param member 要更新的会员对象
     * @return 成功更新返回 true，否则返回 false
     * @throws SQLException SQL异常
     */
    public boolean update(MemberDetail member) throws SQLException {
        String sql = "UPDATE member_detail SET real_name=?, phone=?, id_card=?, gender=?, "
                + "contact_name=?, contact_phone=? WHERE member_id=?";
        Connection conn = null;
        PreparedStatement ps = null;

        try {
            conn = DBUtil.getConnection();
            ps = conn.prepareStatement(sql);
            ps.setString(1, member.getRealName());
            ps.setString(2, member.getPhone());
            ps.setString(3, member.getIdCard());
            ps.setString(4, member.getGender());
            ps.setString(5, member.getContactName());
            ps.setString(6, member.getContactPhone());
            ps.setInt(7, member.getMemberId());

            int rowsAffected = ps.executeUpdate();
            return rowsAffected > 0;
        } finally {
            DBUtil.close(conn, ps, null);
        }
    }
}